package com.db.springcloud.controller;

import com.db.springcloud.pojo.User;
import com.db.springcloud.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//提供restful服务
@Controller
@RestController
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    DiscoveryClient client;

    @PostMapping("/user/add")
    public boolean addUser(User user){
        return userService.addUser(user);
    }

    @GetMapping("/user/get/{id}")
    public User queryById(@PathVariable("id") int id){
        return userService.queryById(id);
    }

    @GetMapping("/user/getall")
    public List<User> queryAll(){
        return userService.queryAll();
    }

    @GetMapping("/user/getbyid")
    public User getById(int id){
        return userService.queryById(id);
    }

//    注册进来的微服务,获取一些消息
    @RequestMapping("/user/discovery")
    public Object discovery(){
        //获得微服务的列表
        List<String> services = client.getServices();
        //获得具体的微服务
        List<ServiceInstance> instances = client.getInstances("SPRINGCLOUD-PROVIDER-USER");
        System.out.println("instances"+instances.toString());
        System.out.println("services"+services.toString());
        for (ServiceInstance instance : instances) {
            System.out.println(instance.getHost());
            System.out.println(instance.getPort());
            System.out.println(instance.getUri());
        }
        return this.client;
    }
}
